﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class HealthBar : MonoBehaviour
{
    private CharacterCard characterCard;

    [Header("图片组件")]
    [SerializeField] private Image bg;
    [SerializeField] private Image effect;
    [SerializeField] private Image hp;

    [Header("属性")]
    [SerializeField] private float buff = 0.01f;
    [SerializeField] private float maxHp;
    private float currentHp;

    public float CurrentHp
    {
        get => currentHp;
        private set
        {
            currentHp = Mathf.Clamp(value, 0, maxHp);
            OnHealthUpdated?.Invoke(currentHp, maxHp);
        }
    }

    public float MaxHp => maxHp;

    public static event Action<float, float> OnHealthUpdated;

    public void SetCharacterCard(CharacterCard card)
    {
        if (card == null)
        {
            Debug.LogError("Attempted to set a null CharacterCard!");
            return;
        }

        characterCard = card;
        CardDisplay cardDisplay = GetComponent<CardDisplay>();
        if (cardDisplay == null)
        {
            Debug.LogError("CardDisplay component is missing on this GameObject!");
            return;
        }

        cardDisplay.card = characterCard;
        cardDisplay.ShowCard();
    }


    void Start()
    {
        if (characterCard != null)
        {
            maxHp = characterCard.healthPoint;
            currentHp = maxHp;
        }
        else
        {
            Debug.LogWarning("CharacterCard is null in HealthBar.Start!");
        }
    }

    void Update()
    {
        if (hp.fillAmount != CurrentHp / MaxHp && !isHpUpdating)
        {
            StartCoroutine(UpdatePlayerHealthyUI());
        }
    }

    private bool isHpUpdating = false;

    private IEnumerator UpdatePlayerHealthyUI()
    {
        isHpUpdating = true;
        float targetFill = CurrentHp / MaxHp;

        while (effect.fillAmount > targetFill)
        {
            effect.fillAmount -= buff;
            yield return new WaitForSeconds(0.01f);
        }

        effect.fillAmount = targetFill;
        hp.fillAmount = targetFill;

        isHpUpdating = false;
    }

    private void OnEnable()
    {
        GlobalEventHandler.AddHealthyUI += OnHealthyUIAdd;
        GlobalEventHandler.DeleteHealthyUI += OnHealthyUIDelete;
    }

    private void OnDisable()
    {
        GlobalEventHandler.AddHealthyUI -= OnHealthyUIAdd;
        GlobalEventHandler.DeleteHealthyUI -= OnHealthyUIDelete;
    }

    private void OnHealthyUIAdd(float addHealthyValue)
    {
        if (addHealthyValue <= 0) return;
        CurrentHp += addHealthyValue;
    }

    private void OnHealthyUIDelete(float deleteHealthyValue)
    {
        if (deleteHealthyValue <= 0) return;
        CurrentHp -= deleteHealthyValue;
    }
}